package top.songxs.gmall.cart.biz.impl;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import top.songxs.gmall.cart.biz.CartRpcService;
import top.songxs.gmall.cart.entity.CartItem;
import top.songxs.gmall.cart.vo.AddCartSuccessVo;
import top.songxs.gmall.cart.vo.UserAuthInfoVo;
import top.songxs.gmall.common.execption.GmallException;
import top.songxs.gmall.common.result.Result;
import top.songxs.gmall.common.result.ResultCodeEnum;
import top.songxs.gmall.common.util.UserAuthUtil;
import top.songxs.gmall.feign.product.SkuInfoFeignClient;
import top.songxs.gmall.product.entity.SkuInfo;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartRpcServiceImpl implements CartRpcService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private SkuInfoFeignClient skuInfoFeignClient;


    @Override
    public AddCartSuccessVo addCart(Long skuId, Integer skuNum) {
        Result<SkuInfo> result = skuInfoFeignClient.getSkuInfo(skuId);
        SkuInfo skuInfo = result.getData();
        String cartRedisKey = this.buildCardKey();
        CartItem cartItem = null;
        Boolean aBoolean = redisTemplate.opsForHash().hasKey(cartRedisKey, String.valueOf(skuId));
        List<Object> values = redisTemplate.opsForHash().values(cartRedisKey);
        if (skuNum > 10 || skuNum < 0) {
            throw new GmallException(ResultCodeEnum.SYSTEM_ERROR);
        }
        if (aBoolean) {
            //如果redis中存在此商品，则对数量进行累加
            String cartItemJSON = (String) redisTemplate.opsForHash().get(cartRedisKey, String.valueOf(skuId));
            CartItem cartItem2 = JSON.parseObject(cartItemJSON, CartItem.class);
            int count = cartItem2.getSkuNum() + skuNum;
            if (count>10){
                cartItem2.setSkuNum(10);
            }
            cartItem2.setSkuNum(count);
            redisTemplate.opsForHash().put(cartRedisKey, String.valueOf(skuId), JSON.toJSONString(cartItem2));
        } else {
            List<Object> size = redisTemplate.opsForHash().values(cartRedisKey);
            if (size.size() < 4) {
                //不存在就新增
                cartItem = new CartItem();
                cartItem.setId(skuInfo.getId());
                cartItem.setSkuId(skuInfo.getId());
                cartItem.setCartPrice(skuInfo.getPrice());
                cartItem.setSkuPrice(skuInfo.getPrice());
                cartItem.setSkuNum(skuNum);
                cartItem.setImgUrl(skuInfo.getSkuDefaultImg());
                cartItem.setSkuName(skuInfo.getSkuName());
                cartItem.setIsChecked(1);
                cartItem.setCreateTime(new Date());
                cartItem.setUpdateTime(new Date());
                // 把这个购物项数据存储到Redis中
                redisTemplate.opsForHash().put(cartRedisKey, String.valueOf(skuId), JSON.toJSONString(cartItem));
            } else {
                //超过了购物车的上限了不让添加了
                System.out.println();
            }
        }

        // 创建AddCartSuccessVo对象，封装响应结果
        AddCartSuccessVo addCartSuccessVo = new AddCartSuccessVo();
        addCartSuccessVo.setSkuInfo(skuInfo);
        addCartSuccessVo.setSkuNum(skuNum);

        // 返回
        return addCartSuccessVo;
    }

    @Override
    public void deleteChecked() {
        String key = buildCardKey();
        List<Object> values = redisTemplate.opsForHash().values(key);
        values.stream().forEach(obj -> {
            String cartJSON = obj.toString();
            CartItem cartItem = JSON.parseObject(cartJSON, CartItem.class);
            if (cartItem.getIsChecked() == 1) {
                redisTemplate.opsForHash().delete(key, String.valueOf(cartItem.getId()));
            }
        });
    }

    @Override
    public List<CartItem> findAllCheckedCartItem() {
        String cartKey = this.buildCardKey();//构建redis购物车里的key
        List<Object> values = redisTemplate.opsForHash().values(cartKey);
        List<CartItem> result = values.stream().map(obj -> {
            String jsonString = obj.toString();
            CartItem cartItem = JSON.parseObject(jsonString, CartItem.class);
            return cartItem;
        }).filter(cartItem -> cartItem.getIsChecked()==1)
          .collect(Collectors.toList()); //获取所有的cartItem，过滤掉，只要选中的


        return result;
    }

    private String buildCardKey() {
        UserAuthInfoVo userAuthInfo = UserAuthUtil.getUserAuthInfo();
        String userId = userAuthInfo.getUserId();
        String userTempId = userAuthInfo.getUserTempId();
        if (userId != null) {
            return "cart:info:" + userId;
        } else {
            return "cart:info:" + userTempId;
        }
    }
}
